﻿using System;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using log4net;

namespace ProductIntroduction.Utils
{
    public class Common
    {
        private static readonly ILog logger =
            LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public static void WriteLogInfo(string title, string info)
        {
            try
            {
                logger.Info("--------------------------------");
                logger.Info(title + ": " + info);
                logger.Info("--------------------------------");
            }
            catch (Exception ex)
            {
                WriteLogError(MethodBase.GetCurrentMethod().Name, ex.Message);
            }
        }

        public static void WriteLogError(string title, string exception)
        {
            if (logger.IsErrorEnabled)
            {
                logger.Error("--------------------------------");
                logger.Error(title + ": " + exception);
                logger.Error("--------------------------------");
            }
        }

        public static string StringToMd5(string value)
        {
            var md5 = string.Empty;
            var md5Hasher = new MD5CryptoServiceProvider();
            var encoder = new System.Text.UTF8Encoding();
            byte[] hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(value));

            return hashedBytes.Aggregate(md5, (current, b) => current + b.ToString("X2"));
        }
    }
}